/**
 * 
 */
package org.mips.Sirius.provider.connection;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.mips.Sirius.provider.ProviderConnection;
import org.mips.Sirius.provider.ProviderException;

/**
 * @author mips
 * 
 */
public class HttpPOSTConnection implements ProviderConnection {

	URL sourceURL;
	String encoding;

	public HttpPOSTConnection(URL sourceURL, String encoding) {
		this.sourceURL = sourceURL;
		this.encoding = encoding;
	}

	@Override
	public String send(String request) throws ProviderException {

		String response = "";

		try {
			String data = URLEncoder.encode("request", encoding) + "="
					+ URLEncoder.encode(request, encoding);

			URLConnection connection = sourceURL.openConnection();
			connection.setDoOutput(true);
			connection.setConnectTimeout(3000); // 3 seconds, tops
			OutputStreamWriter wr = new OutputStreamWriter(connection
					.getOutputStream());
			wr.write(data);
			wr.flush();

			BufferedReader rd = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));

			String line;
			while ((line = rd.readLine()) != null) {
				response = response + line;
			}
			wr.close();
			rd.close();

		} catch (Exception e) {
			throw new ProviderException(e, "Couldn't send request");
		}

		return response;
	}

}
